package rsj.api.test;

import com.alibaba.fastjson.JSONObject;
import com.rlyy.aibase.db.Dbink;
import com.rlyy.aibase.utils.base.Box;
import com.rlyy.aibase.utils.base.MapNode;
import common.util.Assert;
import common.util.BoxUtil;
import common.util.DateFormat;
import common.util.http.HttpUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import rsj.api.ApiVariable;
import rsj.api.user.BaseLink;
import rsj.context.ApplicationContextUtil;
import rsj.dao.TestLogDao;
import rsj.db.PostgresqlConn;
import rsj.properties.FileServiceProperties;
import rsj.utils.RedisUtils;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

/**
 * 查看测试文件上传结果
 *
 * @author yuanqinglong
 * @since 2020/10/20 13:50
 */
@Deprecated
@RestController
public class GetUploadResults extends BaseLink {

    private static final TestLogDao TEST_LOG_DAO = TestLogDao.getInstance();
    public static final int INTERVAL = 30;


    @Override
    @RequestMapping(value = "rsj_data_get_upload_result")
    public Box executeLink(Box box) {
        String tid = box.getNode("$tid");
        MapNode data = box.getMapNode("data");
        String logId = data.getValue("log_id");
        if (StringUtils.isEmpty(logId)) {
            return BoxUtil.errorBox(box, "参数不足");
        }
        MapNode info = TEST_LOG_DAO.getInfoByLogId(logId);
        if (info == null) {
            return BoxUtil.errorBox(box, "此记录不存在");
        }
        String logTime = info.getValue("Log_Time").replace(".0", "");
        String logResId = info.getValue("Log_Res_Id");
        String logParId = info.getValue("Log_Par_Id");
        Map<String, String> jsonHeader = HttpUtil.createJSONHeader();
        Connection conn = PostgresqlConn.getConnection();
        try {
            String fileServiceUrl = ApplicationContextUtil.getApplicationContext().getBean(FileServiceProperties.class).getFileServiceUrl();
            Assert.isNotBlank(fileServiceUrl,"找不到文件服务地址");
            JSONObject logResObject = new JSONObject();
            logResObject.put("file_id", logResId);
            String resResult = HttpUtil.post(fileServiceUrl, TestLogDao.createBody(tid,
                    fileServiceUrl, logResObject), jsonHeader);
            logResObject.put("file_id", logParId);
            String parResult = HttpUtil.post(fileServiceUrl, TestLogDao.createBody(tid,
                    fileServiceUrl, logResObject), jsonHeader);
            JSONObject resObject = JSONObject.parseObject(Optional.ofNullable(resResult).orElse("{}"));
            String resFileStatus = Optional.ofNullable(resObject.getJSONObject("_data_")).map(jsonObject -> jsonObject.getString("file_status")).orElse("");
            JSONObject aprObject = JSONObject.parseObject(Optional.ofNullable(parResult).orElse("{}"));
            String parFileStatus = Optional.ofNullable(aprObject.getJSONObject("_data_")).map(jsonObject -> jsonObject.getString("file_status")).orElse("");
            String redisResult = this.queryRedisResult(logId);
            if (Objects.equals("0", resFileStatus) && Objects.equals("0", parFileStatus)) {
                //计算当前时间和文件上传时间间隔  如果间隔大于30分钟 视为失败。
                LocalDateTime createTime = LocalDateTime.parse(logTime, DateFormat.DATE_TIME_FORMATTER);
                long minute = ChronoUnit.MINUTES.between(createTime, LocalDateTime.now());
                if (minute > INTERVAL) {
                    TEST_LOG_DAO.updateTestLogResult(conn, logId, "0");
                    return BoxUtil.errorBox(box, "文件解析失败无法查看");
                }
                return BoxUtil.errorBox(box, "文件正在解析请稍后查询");
            }
        } catch (IOException | SQLException e) {
            e.printStackTrace();
            return BoxUtil.errorBox(box, "服务器忙请稍后再试");
        } finally {
            Dbink.close(conn);
        }
        return BoxUtil.successBox(box, "成功");
    }

    /**
     * 查询此次数据测试解析的结构状态
     *
     * @param logId 日志id
     * @return 状态
     * 0：等待中
     * 1：开始任务
     * 2：任务完成，成功
     * 98：任务失败，解析失败，上传原文件
     * 99：任务失败，调用失败，无任何文件上传
     */
    private String queryRedisResult(String logId) {
        String taskName = "rsjmq:" + logId;
        return RedisUtils.getString(taskName);
    }


    public static void main(String[] args) {
        String s = "2020-10-22 09:37:37.0".replace(".0", "");
        LocalDateTime parse = LocalDateTime.parse(s, DateFormat.DATE_TIME_FORMATTER);
        System.out.println(parse);
    }
}
